/*
* Copyright (c) 2025 Shenzhen Kaihong Digital Industry Development Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#include "SAServiceProxy.h"
#include "ISAService.h"
#include "log.h"

namespace OHOS {
namespace OHMW {
DEFINE_OHMW_LOG_LABEL("OhmwSaServiceProxy");

OhmwSaServiceProxy::OhmwSaServiceProxy(const sptr<IRemoteObject>& impl) : IRemoteProxy<IOhmwSaService>(impl),
    remoteDied_(false)
{
    if (impl) {
        if (!impl->IsProxyObject()) {
            OHMW_LOGW("not proxy object!");
            return;
        }
        if (!impl->AddDeathRecipient(this)) {
            OHMW_LOGW("AddDeathRecipient failed!");
            return;
        }
    }
}

OhmwSaServiceProxy::~OhmwSaServiceProxy() {}

ErrCode OhmwSaServiceProxy::LaunchOhmwServer(MWServer::Type type) {
    if (remoteDied_) {
        OHMW_LOGE("Failed to `%{public}s`, remote service is died!", __func__);
        return OHMW_SA_ERR_FAILED;
    }

    MessageOption option;
    MessageParcel data;
    MessageParcel reply;
    if (!data.WriteInterfaceToken(GetDescriptor())) {
        OHMW_LOGE("Write interface token error: %{public}s", __func__);
        return OHMW_SA_ERR_FAILED;
    }
    data.WriteInt32(0);
    int error = Remote()->SendRequest(static_cast<uint32_t>(InterfaceCode::OHMW_SA_CMD_LAUNCH_OHMW_SERVER),
        data, reply, option);
    if (error != ERR_NONE) {
        OHMW_LOGE("LaunchOhmwServer(%{public}d) failed, error code is %{public}d",
            static_cast<int32_t>(InterfaceCode::OHMW_SA_CMD_LAUNCH_OHMW_SERVER), error);
        return OHMW_SA_ERR_FAILED;
    }
    
    int exception = reply.ReadInt32();
    if (exception) {
        return OHMW_SA_ERR_FAILED;
    }
    return ErrCode(reply.ReadInt32());
}

void OhmwSaServiceProxy::OnRemoteDied(const wptr<IRemoteObject>& remote) {
    OHMW_LOGW("Remote service is died! remote: %{private}p", &remote);
    remoteDied_ = true;
}
}
}
